package pe.gob.osinergmin.component;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import pe.gob.osinergmin.R;
import pe.gob.osinergmin.activity.MenuActivity;

public class MenuListAdapter extends BaseAdapter implements View.OnClickListener {

    private Activity activity;
    private List data;
    private LayoutInflater inflater = null;
    public Resources res;
    MenuListItem tmpItem = null;

    public MenuListAdapter(Activity activity, List data, Resources res) {
        this.activity = activity;
        this.data = data;
        this.res = res;

        this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        if(data.size() <= 0)
            return 1;
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        MenuListViewHolder holder;

        if( convertView == null){
            view = inflater.inflate(R.layout.item_menu, null);

            holder = new MenuListViewHolder();
            holder.img = (ImageView) view.findViewById(R.id.menuitem_img);
            holder.title = (TextView) view.findViewById(R.id.menuitem_title);
            holder.description = (TextView) view.findViewById(R.id.menuitem_description);

            view.setTag(holder);
        }else{
            holder = (MenuListViewHolder) view.getTag();
        }

        if(data.size() <= 0){
            holder.title.setText("No Data");
        }else{
            tmpItem = null;
            tmpItem = (MenuListItem) data.get(position);

            holder.title.setText( tmpItem.getTitle() );
            holder.description.setText( tmpItem.getDescription() );
            holder.img.setImageResource( tmpItem.getImg() );

            view.setOnClickListener(new OnItemClickListener(position));
        }

        return view;
    }

    @Override
    public void onClick(View v) {
        Log.v("MenuListAdapter", "=====Row button clicked=====");
    }

    private class OnItemClickListener  implements View.OnClickListener {
        private int mPosition;

        OnItemClickListener(int position){
            mPosition = position;
        }

        public void onClick(View arg0) {

            MenuActivity menuActivity = (MenuActivity) activity;
            menuActivity.onItemClick(mPosition);
        }
    }
}
